import { config } from '../config.js'

const { baseUrl, appKey } = config
const tips = {
  1: '抱歉，出现了一个错误',
  1005: '不正确的开发者key',
  3000: '该期内容不存在'
}

class HTTP {
  request (params) {
    const { url, method, data, success } = params
    wx.request({
      url: `${baseUrl}${url}`,
      method,
      data,
      header: {
        'content-type': 'application/json',
        appKey
      },
      success: res => {
        const { statusCode, data } = res
        if (statusCode.toString().startsWith('2')) {
          success && success(data)
        } else {
          this._showError(data.error_code)
        }
      },
      fail: err => this._showError(1)
    })
  }

  _showError (errorCode = 1) {
    wx.showToast({
      title: tips[errorCode],
      icon: 'none',
      duration: 2000
    })
  }
}

export { HTTP }
